package org.pro.Net;

import org.pro.Model.Shot;
import org.pro.Model.Tank;
import org.pro.Model.WarData;

import java.io.IOException;
import java.io.ObjectInput;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.List;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.LinkedBlockingQueue;

public class Server {
    public ServerSocket server;//创建服务器套接字
    public ObjectInputStream in;
    public ObjectOutputStream out;
    public List<ClientHand> clients = new CopyOnWriteArrayList<>();//处理一下子线程
    public boolean running = false;
    public WarData  warData;
    public int peoplecount=0;
    public boolean gamego=false;
    // 创建一个消息队列，用于存放客户端发送的消息
    public BlockingQueue<Natway> messageQueue = new LinkedBlockingQueue<>();

    public Server(int port) throws IOException {
        this.server = new ServerSocket(port); // 在指定端口启动ServerSocket
        warData=new WarData();
    }

    //启动服务器并接受连接
    public void start() {
        running = true;
        System.out.println("服务器以及启动了！！！");
        while (peoplecount<2) {
            try {
                Socket clientSocket = server.accept(); // 接受客户端连接
                System.out.println("一个客户端进行连接咯:" + clientSocket.getInetAddress());
                // 创建客户端处理线程并启动
                ClientHand clientHandler = new ClientHand(clientSocket, peoplecount, this);
                clients.add(clientHandler);
                new Thread(clientHandler).start();
                Natway msg=Natway.creatReady(peoplecount,warData);
                peoplecount++;
                clientHandler.sendMessage(msg);
            } catch (IOException e) {
                if (running) {
                    System.out.println("Error accepting client connection: " + e.getMessage());
                }
            }
        }
    }
    //启动游戏
    // 在start()方法后添加
    public void run()
    {
        new Thread(this::Procemessage).start();
    }
    public void startGameLoop() {
       if(!gamego)
       {
            gamego=true;
            new Thread(() -> {
                long lastUpdate=System.currentTimeMillis();
                int fps = 60;//理论帧数
                while (running) {
                    long interval = 1000 / fps;//理论间隔
                    long curr = System.currentTimeMillis();
                    long _time = curr - lastUpdate;
                    if (_time < interval) {
                        // 不到刷新时间，休眠
                        try {
                            Thread.sleep(1);
                        } catch (Exception e) {
                        }
                    } else {
                        // 更新游戏状态
                        lastUpdate = curr;
                        // 流逝时间
                        float dt = _time * 0.001f;
                        //updatePositions(dt);
                        warData.updatePositions(dt);
                        // 碰撞检测
                        // CollisionDetection();
                        warData.CollisionDetection();
                        // 依据元素的状态，更新数据区
                        warData.updateDataSet();
                        // 广播游戏状态
                        broadcastGameState(dt);
                        try {
                            Thread.sleep(16); // 保持约60Hz更新16改为33
                        } catch (InterruptedException e) { /* 处理异常 */ }
                    }
                }
            }).start();
        }

    }

    //接受消息
//    public void Recmessage() {
//        while (running) {
//            try {
//                Object obj = in.readObject();
//                if (obj instanceof Natway) {
//                    Natway msg = (Natway) obj;
//                    messageQueue.put(msg);
//                    // 根据msg的内容进行相应处理
//                    // 比如，如果是坦克移动指令或者其他处理
//                } else {
//                    // 处理其他类型的消息
//                    System.out.println("Received unknown object: " + obj);
//                }
//            } catch (IOException e) {
//                throw new RuntimeException(e);
//            } catch (ClassNotFoundException e) {
//                throw new RuntimeException(e);
//            } catch (InterruptedException e) {
//                throw new RuntimeException(e);
//            }
//        }
//    }
    //处理消息
    public void Procemessage()
    {
        while(running)
        {
            try {
                Natway msg = messageQueue.take();
                Tank tank = msg.playerid == 0 ? warData.userTank : warData.enemyTank;
                switch (msg.type){
                    case TANK_MOVE:
                        handleTankMovement(msg);
                        break;
                    case TANK_SHOOT:
                        Shot shot = new Shot(tank, 200.0);
                        warData.elements.add(shot);
                        break;
                    case TANK_DIR:
                        tank.turretDir=msg.tandir;
                        break;
                    case READY:
                        if(peoplecount==2)
                        {
                            this.startGameLoop();
                            System.out.println("证明没有卡死");
                        }
                        break;
                    default:
                        break;
                }
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        }
    }
    //发送消息
//    public void Sendmessage(Natway msg)
//    {
//        try{
//            out.writeObject(msg);
//            out.flush();
//        }
//        catch (IOException e) {
//            e.printStackTrace();
//        }
//    }

    //广播游戏状态
    public void broadcastGameState(float dt)
    {
        try {
            WarData copyData = warData.deepCopy(); // 深拷贝
            Natway stateMsg = Natway.creatGame(copyData, dt);
            for (ClientHand client : clients) {
                client.sendMessage(stateMsg);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    public void handleTankMovement(Natway msg) {
        Tank tank;
        if(msg.playerid==0)
            tank=warData.userTank;
        else
            tank=warData.enemyTank;
        tank.moving=msg.moving;
            switch (msg.dir) {
                case "左":
                    tank.dir = tank.turretDir - 90;
                    break;
                case "右":
                    tank.dir = tank.turretDir + 90;
                    break;
                case "上":
                    tank.dir = tank.turretDir;
                    break;
                case "下":
                    tank.dir = tank.turretDir - 180;
                    break;
                default:
                    break;
        }

    }
}
